package com.alifi.crm.web.home.screen;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.alibaba.buc.sso.client.util.SimpleUserUtil;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.common.lang.StringUtil;
import com.alibaba.common.logging.Logger;
import com.alibaba.common.logging.LoggerFactory;
import com.alibaba.platform.buc.sso.common.dto.SimpleSSOUser;
import com.alifi.crm.biz.lottery.LotteryManager;
import com.alifi.crm.dal.object.EmployeeDO;
import com.alifi.crm.dal.object.WinRecordDO;

/**
 * 
 * 
 * @author wb_liangzhou.yan
 * @version $Id: Lottery.java, v 0.1 2013-4-24 下午04:43:42 wb_liangzhou.yan Exp $
 */
public class Lottery {
    
    private static final Logger      logger = LoggerFactory.getLogger(Guess.class);   
    
    @Resource(name = "lotteryManager")
    private LotteryManager lotteryManager;
    
    public void execute(HttpServletRequest request, HttpServletResponse response,final Context ctx){
        try{
            if(StringUtil.equalsIgnoreCase((String)ctx.get("action"), "true")){   //如果经过action，直接返回
                return;
            }
            
            SimpleSSOUser user = SimpleUserUtil.findUser(request);   // 姓名: lastName   花名: nickNameCn 
            
            if((user==null)||StringUtil.isBlank(user.getEmpId())){   //检查
                logger.error("没有获得您的登录信息，请与管理员联系.电话: 13805730726");
                ctx.put("error","没有获得您的登录信息，请与管理员联系.电话: 13805730726");
                return;
            }
            
            //加上访问日志
            lotteryManager.insertLog(user.getEmpId(), user.getLastName(), user.getNickNameCn());
            
            ctx.put("user", user);
            ctx.put("employeeNum", user.getEmpId());
            
            //获取会员信息
            int times = 0;
            EmployeeDO employee = lotteryManager.getEmployeeInfo(user.getEmpId());
            if(employee != null){
                times = employee.getAvailLotteryTime().intValue();
            }
            ctx.put("times", times);
            //获取中奖返利信息
            ctx.put("userWin",getUserWinRecords(user.getEmpId()));
            
            //获取中奖信息
            ctx.put("lotteryInfos", convertToListString(lotteryManager.getWinRecords()));
            
            //增加转发次数, 66018仅仅做为测试
            //String visitor_num = request.getParameter("visitor_num");
            //if (visitor_num != null && user.getEmpId().equals("66018")) {
            //	lotteryManager.addTransmitLog(request.getParameter("employee_num"), visitor_num);
            //} else {
                lotteryManager.addTransmitLog(request.getParameter("employee_num"), user.getEmpId());
            //}
        }catch (Exception e){
            ctx.put("error", e.getMessage());
            logger.error(e);  
        }
        
    }
    
    private String getUserWinRecords(String employeeNum){
        String total = "0";
        //获取个人中奖纪录
        List<WinRecordDO> winRecords = lotteryManager.selectByEmployeeNum(employeeNum);
        if(CollectionUtils.isNotEmpty(winRecords)){
            int perTotal = 0;
            for (WinRecordDO winRecord : winRecords) {
                if(StringUtil.isNotBlank(winRecord.getPrizeType())){
                    perTotal += Integer.valueOf(winRecord.getPrizeType());
                }
            }
            total = String.valueOf(perTotal);
        }
        return total;
    }
    
    private List<String> convertToListString(List<WinRecordDO> winRecords){
        List<String> lotteryInfos = new ArrayList<String>();
        if(CollectionUtils.isEmpty(winRecords)){
            return null;
        }
        for(WinRecordDO winRecord : winRecords){
            StringBuffer sb = new StringBuffer();
            String name = "";
            if(StringUtils.isNotBlank(winRecord.getNickName())){
                name = convertString(winRecord.getNickName());
            }else{
                name = convertString(winRecord.getRealName());
            }
            sb.append(name).append(" 获得").append(winRecord.getPrizeType()).append("%返利");
            lotteryInfos.add(sb.toString());
        }
        
        return lotteryInfos;
    }
    
    
    private String convertString(String str){
        if(StringUtils.isNotBlank(str)){
            if(str.length() > 1){
                return str.replace(str.substring(str.length() -1), "*");
            }
        }
        
        return str;
    }
    
}
